﻿using System.Runtime.Serialization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace Inovout.Serialization
{
    public class BinarySerializer : ISerializer
    {
        public Stream Serialize(object obj)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, obj);
            return stream;
        }
        public byte[] SerializeToByteArray(object obj)
        {
            using (Stream stream = Serialize(obj))
            {
                stream.Position = 0;
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }

        public T Deserialize<T>(byte[] buffer)
        {
            IFormatter formatter = new BinaryFormatter();
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(buffer, 0, buffer.Length);
                stream.Position = 0;
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}
